#!/usr/bin/env python3
"""
全局加解密客户端示例
演示如何与支持全局加解密的API服务器交互
"""

import requests
import json
from utils import EncryptionUtil
from config import Config

class ApiClient:
    """API客户端，支持自动加解密"""
    
    def __init__(self, base_url, encryption_key=None, use_encryption=True):
        """
        初始化API客户端
        
        Args:
            base_url: API服务器地址
            encryption_key: 加密密钥
            use_encryption: 是否使用加密
        """
        self.base_url = base_url.rstrip('/')
        self.use_encryption = use_encryption
        self.encryption_util = None
        
        if use_encryption and encryption_key:
            self.encryption_util = EncryptionUtil(encryption_key)
    
    def _prepare_request(self, data):
        """准备请求数据"""
        if not self.use_encryption or not self.encryption_util:
            return data
        
        # 加密请求数据
        encrypted_data = self.encryption_util.encrypt_json(data)
        return {
            "encrypted": True,
            "data": encrypted_data
        }
    
    def _process_response(self, response):
        """处理响应数据"""
        try:
            response_data = response.json()
            
            # 检查响应是否加密
            if response_data.get('encrypted', False) and self.encryption_util:
                # 解密响应数据
                decrypted_data = self.encryption_util.decrypt_json(response_data['data'])
                return decrypted_data
            else:
                return response_data
                
        except Exception as e:
            print(f"处理响应失败: {str(e)}")
            return None
    
    def post(self, endpoint, data=None):
        """发送POST请求"""
        url = f"{self.base_url}{endpoint}"
        
        if data:
            request_data = self._prepare_request(data)
        else:
            request_data = {}
        
        try:
            response = requests.post(
                url,
                json=request_data,
                headers={'Content-Type': 'application/json'}
            )
            
            return {
                'status_code': response.status_code,
                'data': self._process_response(response)
            }
            
        except Exception as e:
            return {
                'status_code': 0,
                'error': str(e)
            }
    
    def get(self, endpoint):
        """发送GET请求"""
        url = f"{self.base_url}{endpoint}"
        
        try:
            response = requests.get(url)
            
            return {
                'status_code': response.status_code,
                'data': self._process_response(response)
            }
            
        except Exception as e:
            return {
                'status_code': 0,
                'error': str(e)
            }

def demo_encrypted_client():
    """演示加密客户端"""
    print("🔐 加密客户端演示")
    print("=" * 50)
    
    # 创建加密客户端
    client = ApiClient(
        base_url="http://localhost:8000",
        encryption_key=Config.ENCRYPTION_KEY,
        use_encryption=True
    )
    
    # 1. 测试健康检查（不加密）
    print("1. 健康检查...")
    result = client.get("/health")
    print(f"状态码: {result['status_code']}")
    print(f"响应: {result.get('data', result.get('error'))}")
    
    # 2. 测试登录（加密）
    print("\n2. 登录测试...")
    login_data = {
        "username": "test@example.com",
        "password": "test123456"
    }
    
    result = client.post("/api/auth/login", login_data)
    print(f"状态码: {result['status_code']}")
    print(f"响应: {result.get('data', result.get('error'))}")
    
    # 3. 测试发送短信（加密）
    print("\n3. 发送短信...")
    sms_data = {
        "phone": "13800138001",
        "purpose": "login"
    }
    
    result = client.post("/api/auth/send-sms", sms_data)
    print(f"状态码: {result['status_code']}")
    print(f"响应: {result.get('data', result.get('error'))}")

def demo_normal_client():
    """演示普通客户端"""
    print("\n📤 普通客户端演示")
    print("=" * 50)
    
    # 创建普通客户端
    client = ApiClient(
        base_url="http://localhost:8000",
        use_encryption=False
    )
    
    # 1. 测试健康检查
    print("1. 健康检查...")
    result = client.get("/health")
    print(f"状态码: {result['status_code']}")
    print(f"响应: {result.get('data', result.get('error'))}")
    
    # 2. 测试登录（不加密）
    print("\n2. 登录测试...")
    login_data = {
        "username": "test@example.com",
        "password": "test123456"
    }
    
    result = client.post("/api/auth/login", login_data)
    print(f"状态码: {result['status_code']}")
    print(f"响应: {result.get('data', result.get('error'))}")

def main():
    """主函数"""
    print("🚀 全局加解密客户端示例")
    print("=" * 50)
    
    # 演示加密客户端
    demo_encrypted_client()
    
    # 演示普通客户端
    demo_normal_client()
    
    print("\n✅ 演示完成")
    print("=" * 50)
    print("总结:")
    print("- 加密客户端：自动加密请求，自动解密响应")
    print("- 普通客户端：直接发送请求，直接接收响应")
    print("- 服务器同时支持两种模式，自动识别并处理")
    print("- 健康检查等特殊端点始终不加密")

if __name__ == '__main__':
    main()